package com.baizhi.controller;


import com.baizhi.FileImg;
import com.baizhi.service.ImgService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class ImgController {
    @Autowired
    private ImgService imgService;
    @RequestMapping("/function1")
    public String shangChuan(MultipartFile Filename, String oldname,String descript){
        String filename = Filename.getOriginalFilename();//得到用户上传时的文件名字
        UUID uuid = UUID.randomUUID();
        String newName=uuid+filename;
        File ta=new File("e:/"+newName+"");
        try {
            Filename.transferTo(ta);
        } catch (IOException e) {
            e.printStackTrace();
        }
        imgService.insert(new FileImg(1,filename,newName,null,descript));
        return "redirect:/show.do";
    }
    @RequestMapping("show")
    public String a(Model model){
        List<FileImg> fileImgs = imgService.selectAll();
        model.addAttribute("c",fileImgs);
        return "forward:/file.jsp";
    }
    @RequestMapping("/download")
    public void down(String filename, HttpServletResponse response){
        //通过文件名转化为文件
        File source=new File("e:/"+filename);
        //设置相应格式和文字的名字
        response.setHeader("content-disposition","attachment;fileName="+filename);
        try {
            //把文件放入到response中
            FileUtils.copyFile(source,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/shows")
    @ResponseBody
    public List<FileImg> ab(){
        List<FileImg> fileImgs = imgService.selectAll();
        return fileImgs;
    }
}
